package elitech.vietnam.weatherfashion;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;
import elitech.vietnam.weatherfashion.autoupdate.CheckUpdate;
import elitech.vietnam.weatherfashion.autoupdate.CheckVersionTask;
import elitech.vietnam.weatherfashion.autoupdate.Constants;
import elitech.vietnam.weatherfashion.backgroundtask.NotificationBackGroundService;
import elitech.vietnam.weatherfashion.backgroundtask.ReloadDataService;
import elitech.vietnam.weatherfashion.backgroundtask.ReloadWeatherService;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.notification.GCMIntentService;
import elitech.vietnam.weatherfashion.notification.NotificationPopupWindow;
import elitech.vietnam.weatherfashion.tabs.BaseContainerFragment;
import elitech.vietnam.weatherfashion.tabs.SelfContainerFragment;
import elitech.vietnam.weatherfashion.tabs.SettingsContainerFragment;
import elitech.vietnam.weatherfashion.tabs.StylerContainerFragment;
import elitech.vietnam.weatherfashion.tabs.TodayContainerFragment;
import elitech.vietnam.weatherfashion.tabs.WeeklyContainerFragment;
import elitech.vietnam.weatherfashion.tabs.settings.EditProfileFragment;
import elitech.vietnam.weatherfashion.tabs.settings.SettingsFragment;
import elitech.vietnam.weatherfashion.ultilities.MyDialogHandler;
import elitech.vietnam.weatherfashion.ultilities.Utilities;
import elitech.vietnam.weatherfashion.ultilities.ValueOption;

public class MainActivity extends FragmentActivity implements FragmentTabHost.OnTabChangeListener {

	public static final String TAB_TODAY = "TF";
	public static final String TAB_WEEKLY = "WF";
	public static final String TAB_STYLER = "TS";
	public static final String TAB_SELF = "MF";
	public static final String TAB_SETTINGS = "ST";

	public static final int REQ_CODE_LIB = 10;
	public static final int REQ_CODE_CAM = 11;
	public static final int REQ_CODE_SETTING_RELOAD_WEATHER = 112;
	public static final int REQ_CODE_SETTING_CODE = 113;
	public static final int REQ_CODE_EDIT_PROFILE_ALBUM = 114;
	public static final int REQ_CODE_EDIT_PROFILE_CAMERA = 115;
	public static final int REQ_CODE_EDITPOST = 12;
	public static final int REQ_CODE_NEWPOST = 13;
	public static final int REQ_CODE_LOGIN = 14;

	private FragmentTabHost mTabHost;
	private Intent intentReloadWeatherService;
	private Intent intentReloadDataService;

//	public NotificationPopupWindow mNotiWindow;
	
	int currTab = 0;
	boolean isBackclicked = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		Utils.printDeviceScreenType(this);
		initView();

		/** Hung */
		IntentFilter intentFilter = new IntentFilter(Constants.BROADCAST);
		registerReceiver(myReceiver, intentFilter);
		CheckVersionTask task = new CheckVersionTask(this);
		task.execute("null");

//		mNotiWindow = new NotificationPopupWindow(this);

//		IntentFilter intent = new IntentFilter(Const.RECEIVER_UPDATEBADGE_ACTION);
//		registerReceiver(notiReceiver, intent);
	}

	@Override
	protected void onResume() {
		Utils.Log("Resume Main Activity");

		// Start service reload data
		intentReloadDataService = new Intent(this, ReloadDataService.class);
		startService(intentReloadDataService);
		// //////////////////

		// Start service reload weather
		intentReloadWeatherService = new Intent(this, ReloadWeatherService.class);
		startService(intentReloadWeatherService);
		// /

		// FileOption f = new FileOption(this);
		// WFApplication.getInstance().valueOption = f.ReadOption();
		ValueOption option = GlobalValue.getInstance(this).readOptionInfo();
		super.onResume();
		Utils.Log("onResume() Mainactivity + NotificationBackGroundService2.isRunning=" + NotificationBackGroundService.isRunning);

		MemberDTO user = GlobalValue.getInstance(getApplicationContext()).readUserInfo();
		if (user != null && NotificationBackGroundService.isRunning == false && option.isGetNotification()) {

			//Utilities.startNotificationService(this);
			WFApplication.getInstance().startGCMNotification();
		}

		Utils.Log("LanguageIndex " + option.getLanguageIndex());
		Utils.Log("LanguageCode " + option.getLanguageCode());

		if (option.getLanguageIndex() == 0) {
			option.setLanguageCode(Utilities.convertCountryCodeToLanguageCode(Const.COUNTRY_CODE));
		}

		Utilities.changeConfigLanguage(this, option.getLanguageCode());
	
		Intent intent = getIntent();
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				boolean isReload = intent.getBooleanExtra(SettingsFragment.SETTING_RELOAD, false);
				intent.removeExtra(SettingsFragment.SETTING_RELOAD);
				if (isReload) {
					currTab = 4;
					mTabHost.setCurrentTab(currTab);
				}
			}
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		// stop reload data
		stopService(intentReloadDataService);
		// stop reload weather service
		stopService(intentReloadWeatherService);
	}

	private void initView() {
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

		mTabHost.addTab(mTabHost.newTabSpec(TAB_TODAY).setIndicator(createTabView(MainActivity.this, R.drawable.tab_todayicon)), TodayContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_WEEKLY).setIndicator(createTabView(MainActivity.this, R.drawable.tab_weeklyicon)), WeeklyContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_STYLER).setIndicator(createTabView(MainActivity.this, R.drawable.tab_stlyericon)), StylerContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_SELF).setIndicator(createTabView(MainActivity.this, R.drawable.tab_selficon)), SelfContainerFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec(TAB_SETTINGS).setIndicator(createTabView(MainActivity.this, R.drawable.tab_settingsicon)), SettingsContainerFragment.class, null);

		mTabHost.setOnTabChangedListener(this);

		for (int i = 0; i < mTabHost.getTabWidget().getTabCount(); i++) {
			final int index = i;
			mTabHost.getTabWidget().getChildAt(i).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mTabHost.getCurrentTab() != index)
						mTabHost.setCurrentTab(index);
					else
						popAllTabFragment();
				}
			});
		}

	}

	@Override
	public void onBackPressed() {
		boolean isPopFragment = false;
		BaseContainerFragment base = getCurrentBase();
		if (base != null)
			isPopFragment = base.popFragment();
		String currentTabTag = mTabHost.getCurrentTabTag();

		if (!isPopFragment && !currentTabTag.equals(TAB_TODAY))
			mTabHost.setCurrentTab(0);

		if (!isPopFragment && currentTabTag.equals(TAB_TODAY)) {
			if (isBackclicked) {
//				Intent intent = new Intent(MainActivity.this, NotificationBackGroundService.class);
//				stopService(intent);
				finish();
			} else {
				isBackclicked = true;
				Toast.makeText(this, getString(R.string.click_back_again_to_exit), Toast.LENGTH_SHORT).show();
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						isBackclicked = false;
					}
				}, 2000);
			}
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String data;
		if (intent.hasExtra(GCMIntentService.NOTIFICATION_DATA_TAG) && !(data=intent.getStringExtra(GCMIntentService.NOTIFICATION_DATA_TAG)).equals("")) {
			
		}
	}

	private static View createTabView(final Context context, int resId) {
		View view = LayoutInflater.from(context).inflate(R.layout.tab_mainitem, null);
		Drawable image = context.getResources().getDrawable(resId);
		ImageView item_image = (ImageView) view.findViewById(R.id.tab_item_image);
		item_image.setImageDrawable(image);
		return view;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		int n = requestCode & 0xffff;
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		Intent intent;

		switch (n) {
		case REQ_CODE_EDIT_PROFILE_ALBUM:
			EditProfileFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;

		case REQ_CODE_EDIT_PROFILE_CAMERA:
			EditProfileFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;

		case REQ_CODE_SETTING_CODE:
			SettingsFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;

		case REQ_CODE_SETTING_RELOAD_WEATHER:
			SettingsFragment.THIS.onActivityResult(requestCode, resultCode, data);
			break;

		case REQ_CODE_LIB:
			intent = new Intent(MainActivity.this, NewPostActivity.class);
			intent.putExtra("image", Utils.getPath(data.getData(), this));
			intent.putExtra("request", REQ_CODE_LIB);
			startActivityForResult(intent, REQ_CODE_NEWPOST);
			break;

		case REQ_CODE_CAM:

			Utils.Log(WFApplication.getInstance().todayData == null);
			intent = new Intent(MainActivity.this, NewPostActivity.class);
			intent.putExtra("image", NewPostActivity.CAM_PATH);
			intent.putExtra("request", REQ_CODE_CAM);
			startActivityForResult(intent, REQ_CODE_NEWPOST);
			break;

		case REQ_CODE_NEWPOST:
			getIntent().putExtra("SELF_RELOAD", 1);
			WFApplication.getInstance().stylerAllData = null;
			break;

		case REQ_CODE_LOGIN:
			getIntent().putExtra("SELF_RELOAD", 1);
			// getIntent().putExtra("RETURN_ROOT", 1);
			break;

		case REQ_CODE_EDITPOST:
			if (data.getBooleanExtra("EditPostResult", false)) {
				getIntent().putExtra("SELF_RELOAD", 1);
				getIntent().putExtra("POST_RELOAD", 1);
				WFApplication.getInstance().stylerAllData = null;
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onTabChanged(String tabId) {
		MemberDTO user = GlobalValue.getInstance(getApplicationContext()).readUserInfo();
		if (tabId.equals(TAB_SELF) && (user == null)) {
			new MyDialogHandler().confirm(this, getString(R.string.access_denied_), getString(R.string.request_login), getString(R.string.cancel), getString(R.string.ok), new Runnable() {
				@Override
				public void run() {
					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
					startActivityForResult(intent, REQ_CODE_LOGIN);
				}
			}, new Runnable() {
				@Override
				public void run() {
					mTabHost.setCurrentTab(currTab);
				}
			});
		} else {
			currTab = mTabHost.getCurrentTab();
		}
		if (tabId.equals(TAB_TODAY))
			getIntent().putExtra("TODAY_FIRST_PAGE", 1);

		if (tabId.equals(TAB_WEEKLY))
			getIntent().putExtra("WEEKLY_FIRST_TAB", 1);

		if (tabId.equals(TAB_STYLER))
			getIntent().putExtra("STYLER_FIRST_TAB", 1);

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
//		unregisterReceiver(notiReceiver);
		unregisterReceiver(myReceiver);
	}

	private boolean popAllTabFragment() {
		BaseContainerFragment base = getCurrentBase();
		if (base != null)
			return base.popAllFragment();
		return false;
	}

	public BaseContainerFragment getCurrentBase() {
		String currentTabTag = mTabHost.getCurrentTabTag();
		BaseContainerFragment base = null;
		try {
			if (currentTabTag.equals(TAB_TODAY)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_TODAY));
			} else if (currentTabTag.equals(TAB_WEEKLY)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_WEEKLY));
			} else if (currentTabTag.equals(TAB_STYLER)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_STYLER));
			} else if (currentTabTag.equals(TAB_SELF)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_SELF));
			} else if (currentTabTag.equals(TAB_SETTINGS)) {
				base = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_SETTINGS));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return base;
	}

	/** Hung */

	private BroadcastReceiver myReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			Bundle extras = intent.getExtras();
			final Intent myIntent = new Intent(context, CheckUpdate.class);
			if (extras != null) {
				final int versionCode = extras.getInt(Constants.VERSION_CODE);
				String str = extras.getString(Constants.MESSAGE_INFO);
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle(context.getResources().getString(R.string.app_name));
				builder.setMessage(str);
				builder.setCancelable(false);
				builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Bundle b = new Bundle();
						b.putInt(Constants.VERSION_CODE, versionCode);
						myIntent.putExtras(b);
						Log.e("33333333333333333333333", "3333");
						startActivity(myIntent);
					}

				});
				builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Log.e("444444444444444444444", "44444");
					}

				});
				builder.show();
			}
		}
	};
//	
//	private BroadcastReceiver notiReceiver = new BroadcastReceiver() {
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			Bundle extras = intent.getExtras();
//			if (extras.containsKey("updateBadge") && extras.getString("updateBadge").equals("true"))
//				try {
//					mNotiWindow.updateBadge();
//				} catch (IllegalArgumentException e) {
//					e.printStackTrace();
//				}
//		}
//	};
}
